<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>three.js examples</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <script src="js/jquery-3.5.1.min.js"></script>
    <script src="js/lhgdialog/lhgcore.lhgdialog.min.js"></script>
</head>
<style>


</style>
<body>

<div class="">
    <div class=" left">
        <div class="topx">

            <a href="index.html?path=lot&filename=testfactory.gltf&json=testfactory" target="viewer" >fac</a>

            <a href="index.html?path=lot&filename=LOT9-a-土建.gltf" target="viewer" >LOT9-a-土建</a>
            <a href="index.html?path=lot&filename=LOT9.gltf" target="viewer" >别墅群</a>
            <a href="index.html?path=house&filename=house1.gltf" target="viewer" >模单楼层</a>
            <a href="index.html?path=house&filename=bighouse.gltf" target="viewer" >单房子</a>
            <a href="index.html?path=jp&filename=scene.gltf" target="viewer" >网上案例1</a>
            <a href="index.html?path=house&filename=scene.gltf" target="viewer" >网上案例2</a>
            <a href="index.html?path=lot&filename=lot9a.gltf" target="viewer" >模单楼层</a>

        </div>
    </div>
</div>
<div style="position: relative;top: 52px; left: 0px" id="stat"></div>

<div style="position: absolute; color: #d9edf7  ; top: 120px;">
    选中着色器
    <div class="color" style="background:#AA4631 " ></div>
    <div class="color" style="background:#130AF2 " ></div>
    <div class="color" style="background:#C5B49A " ></div>
    <div class="color" style="background:#6A5ACD " ></div>
    <div class="color" style="background:#E8C279 " ></div>
</div>
<style>
    .color{
        background: #130AF2;
        width: 30px;
        height: 30px;
        border-radius: 4px;
        margin: 10px;
    }
</style>

<script language="JavaScript">
    // 参数接收
    function GetArgsFromHref(keys='')
    {
        let urlinfo=window.location.href; //获取当前页面的url
        let len=urlinfo.length;//获取url的长度
        let offset=urlinfo.indexOf("?");//设置参数字符串开始的位置
        let newsidinfo=urlinfo.substr(offset+1,len)//取出参数字符串 这里会获得类似“id=1”这样的字符串
        let newsids=newsidinfo.split("&");//对获得的参数字符串按照“=”进行分割


        let newArr = {}
        let kv = ''
        for(let i=0;i<newsids.length;i++){
            kv = newsids[i].split("=")
            newArr[kv[0]]=kv[1]

        }
        if(keys && newArr[keys] ){
            return newArr[keys]
        }else{
            return  ""
        }

    }
    // 文件目录  lot&filename=LOT9-a-土建.gltf
    let gltfpath = GetArgsFromHref("path") ? "./gltf/"+GetArgsFromHref("path")+"/":"./gltf/lot/"
    let gltfurl =decodeURI(GetArgsFromHref("filename"))
    gltfurl=gltfurl?gltfurl:"LOT9-a-土建.gltf"

    console.log(3333333333)
    console.log(gltfurl)
</script>

<script type="module">
    // 加载主要js
    import * as THREE from './build/three.module.js';
    // 加载内存仪表盘
    import Stats from './threejs/jsm/libs/stats.module.js';
    // 制作一个地板

    import {
        PlaneGeometry,
        MeshPhongMaterial,
        Mesh
    } from './build/three.module.js';
    import { OrbitControls } from './threejs/jsm/controls/OrbitControls.js';
    import { GLTFLoader } from './threejs/jsm/loaders/GLTFLoader.js';
    // 动态仪表盘
    import { GUI } from './threejs/jsm/libs/dat.gui.module.js';

    import {
        DirectionalLight,
        DirectionalLightHelper,
        HemisphereLight,
        HemisphereLightHelper
    } from './build/three.module.js';

    let jsondata= {}


    if(GetArgsFromHref("json")){
        $.ajaxSettings.async = false;
        $.getJSON(gltfpath+GetArgsFromHref("json")+".json",function(jsonObj){

            jsondata = jsonObj

        })
        console.log(jsondata)

    }
    console.log("jjjjjjjjjsssssssssssooooooonnnnnnnnnn")
    console.log(jsondata)


    // 当前选中颜色index
    let colorIndex =0
    // 颜色数组
    let colorArr =["#AA4631","#130AF2","#C5B49A","#6A5ACD","#E8C279"]
    //点击部件时候 存储旧样式  方便还原
    let oldSelect,oldMaterial;
    // 摄像机 位置
    let cameraPosition={x:100,y:100,z:100}

    let
        // 摄像头
        camera,
        // 场景
        scene,
        // 仪表盘
        gui,
        // 渲染器
        renderer,
        // 地板
        floor,
        // 灯光
        directionalLight,
        // 构件对象
        gltfobj,
        // 摄像旋转控制
        controls,
        // 内存显示器
        stats,
        // 特殊效果
        composerAll;



    $(function(){
        // 初始化
        init();
        //doinitLight()
        // 灯光
        dolight()
        // dodiban()
        // 渲染
        render();
        doAxsHelper()
    })



    // 染色切换
    $(function(){

        $(".color").click(function(){

            colorIndex=$(this).index()
        })

    })
    // // 初始化灯光
    // function doinitLight() {
    // 	var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.3 );//模拟远处类似太阳的光源
    // 	directionalLight.color.setHSL( 0.1, 1, 0.95 );
    // 	directionalLight.position.set( 0, 200, 0).normalize();
    // 	scene.add( directionalLight );
    //
    // 	var ambient = new THREE.AmbientLight( 0x404040 ); //AmbientLight,影响整个场景的光源
    // 	ambient.position.set(30,30,30);
    // 	scene.add( ambient );
    // }

    // 灯光
    function dolight(){
        // 平行光  模拟太阳光
        directionalLight = new DirectionalLight(0xffffff, 0.5);
        directionalLight.position.set(1000, 1000, 1000);
        let dhelper = new DirectionalLightHelper(directionalLight, 5, 0xff0000);
        // 光源直接放置于场景之上，光照颜色从天空光线颜色颜色渐变到地面光线颜色。
        let hemisphereLight = new HemisphereLight(0xffffff, 0xffffff, 0.4);
        hemisphereLight.position.set(0, 8, 0);

        scene.add(directionalLight);
        scene.add(hemisphereLight);
        // 光源开启阴影
        directionalLight.castShadow = true;
        directionalLight.shadow.mapSize = new THREE.Vector3(1024, 1024,1024);

    }

    // 坐标轴xyz  辅助器
    function doAxsHelper(){
        let axs  = new THREE.AxesHelper(10)
        scene.add(axs)
    }
    // 初始化实力
    function init() {
        dostats()
        const container = document.createElement( 'div' );
        document.body.appendChild( container );

        camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1,1000 );
        camera.position.set( -10, 8, 20);
        scene = new THREE.Scene();



        doloadGltfs()
        //全局部件颜色改为白色
        //     scene.overrideMaterial= new THREE.MeshLambertMaterial({color:0xffffff})

        doWebGLRenderer()

        // 模型Mesh开启阴影
        container.appendChild( renderer.domElement );

        doOrbiControls();


        window.addEventListener( 'resize', onWindowResize, false );

        //
        // // 内存仪表盘
        // dostats()
        // // 创建画布
        // const container = document.createElement( 'div' );
        // document.body.appendChild( container );
        // // 透视摄像机
        // camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1,1000 );
        // camera.position.set(cameraPosition.x,cameraPosition.y,cameraPosition.z);
        // // 场景
        // scene = new THREE.Scene();
        // //全局部件颜色改为白色
        // //     scene.overrideMaterial= new THREE.MeshLambertMaterial({color:0xffffff})
        // let i = 0
        // // scene.background=new THREE.Color( "#353535" );
        // // 加载模型
        // doloadGltfs()
        // // 渲染器
        // doWebGLRenderer()
        // // 模型Mesh开启阴影
        // container.appendChild( renderer.domElement );
        // // 旋转控制
        // doOrbiControls()
        // // 开启页面点击监控

       // $(document).click(onDocumentMouseDown)
       // window.addEventListener( 'click', onDocumentMouseDown ); // use if there is no animation loop
        // // 页面缩小重置
        // window.addEventListener( 'resize', onWindowResize, false );

    }


    // 摄像头 旋转操控
    function doOrbiControls(){
        controls = new OrbitControls( camera, renderer.domElement );
        controls.addEventListener( 'change', render ); // use if there is no animation loop
        controls.autoRotate = true;//是否自动旋转
        controls.autoRotateSpeed = 0.5;//自动旋转速度，正比
        controls.update();
    }

    // 渲染器
    function doWebGLRenderer(){
        renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        renderer.toneMapping = THREE.ACESFilmicToneMapping;
        renderer.toneMappingExposure = 1;
        renderer.outputEncoding = THREE.sRGBEncoding;
        // 首先渲染器开启阴影
        renderer.shadowMap.enabled = true;
    }

    // 加载gltf 模型
    function  doloadGltfs(){
        $.dialog({
            id: 'loading',
            title: false,
            cancel: false,
            fixed: true,
            lock: true,
            resize: false,
        })
        try{
            let i = 0
            // scene.background=new THREE.Color( "#353535" );
            const loader = new GLTFLoader().setPath(gltfpath );
            loader.load( gltfurl, function ( gltf ) {
                console.log(gltf.scene)
                gltfobj=gltf
                console.log(gltf)
                gltf.scene.traverse( function ( child ) {
                    // console.log("33333333333333333333333")
                    // console.log(child)
                    // console.log(child.userData)
                    // console.log("name:"+child.name+"         uuuiiid"+child.userData.UniqueId)
                    // console.log("999999999999999999999999999999")
                    //
                    // if("f7d54af9-82bd-43de-9210-0e8af02555e6-000099e7"==child.uuid){
                    //     console.log("uuid:"+child.uuid)
                    //
                    // }
                    if ( child.isMesh ) {
                        child.castShadow = true;
                        child.receiveShadow = true;
                    }

                } );
                doSetCameraPosition(gltf)
            } );

        }catch (e) {
            console.log("异常错误")
            console.log(e)
            $.dialog({id:'loading'}).close();

        }
    }




    // 根据模型位置设置  摄像头位置
    function doSetCameraPosition(gltf){
        const box = new THREE.Box3().setFromObject(gltf.scene);
        const size = box.getSize(new THREE.Vector3()).length();
        const center = box.getCenter(new THREE.Vector3());
        // // 旋转重置
        gltf.scene.position.x += (gltf.scene.position.x - center.x);
        gltf.scene.position.y += (gltf.scene.position.y - center.y);
        gltf.scene.position.z += (gltf.scene.position.z - center.z);


        controls.maxDistance = size * 10;
        camera.near = size / 100;
        camera.far = size * 100;

        camera.position.copy(center);
        camera.position.x -= size;
        camera.position.y =  size;
        camera.position.z =  size;;
        console.log(camera.position)

        //
        // camera.position.x += size;
        // camera.position.y += size;
        // camera.position.z += size;
        camera.lookAt(center);
        camera.updateProjectionMatrix();
       gltf.scene.rotation.x=4.7
        dobujian(gltf)

        scene.add( gltf.scene );
        render();

        $.dialog({id:'loading'}).close();
    }



    function onWindowResize() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
        render();
    }


    var projector =new THREE.Raycaster()
    function onDocumentMouseDown(event){

        console.log(3333333333333)
        return
        let objectss =[]
        let mouse = new THREE.Vector2();
        console.log(scene)
        //将鼠标点击位置的屏幕坐标转成threejs中的标准坐标,具体解释见代码释义
        let x = (event.clientX / window.innerWidth) * 2 - 1;
        let y = -(event.clientY / window.innerHeight) * 2 + 1;
        //新建一个三维单位向量 假设z方向就是0.5
        //根据照相机，把这个向量转换到视点坐标系
        var vector = new THREE.Vector3(x, y,0.5).unproject(camera);

        //在视点坐标系中形成射线,射线的起点向量是照相机， 射线的方向向量是照相机到点击的点，这个向量应该归一标准化。
        var raycaster = new THREE.Raycaster(mouse, camera);


        scene.group.forEach(child=>{
            console.log(child)
            if(child in THREE.Mesh){
                objectss.push(child)
            }
        })

        //射线和模型求交，选中一系列直线
        var intersects = raycaster.intersectObjects( objectss);
        console.log('imtersrcts=' + intersects)
        if (intersects.length > 0) {
            //选中第一个射线相交的物体
            let  SELECTED = intersects[0].object;
            var intersected = intersects[0].object;
            console.log(intersects[0].object)
        }
    }




    function dodiban(){
        let floorGeometry = new PlaneGeometry(1000, 1000, 1);
        let floorMaterial = new MeshPhongMaterial({
            color: 0x77F28F,
            //   color:  colorArr[colorIndex],
            shininess: 0,
            // wireframe: true
        });
        floor = new Mesh(floorGeometry, floorMaterial);
        floor.rotation.x = -0.5 * Math.PI;
        floor.position.y = -2.1;

        // 地板接受阴影开启
        floor.receiveShadow = true;
        scene.add(floor);
    }


    // 点击部件
    function  dobujian(gltf){
        console.log("点击部件")
        let raycaster = new THREE.Raycaster();
        let mouse = new THREE.Vector2();
        const selectHandler = function (ev) {

            if(ev.clientX==undefined){
                ev.clientX =ev.originalEvent.changedTouches[0].clientX
            }
            if(ev.clientY==undefined){
                ev.clientY =ev.originalEvent.changedTouches[0].clientY
            }
            // mouse.x = (ev.clientX / window.innerWidth) ;
            // mouse.y = -(ev.clientY / window.innerHeight);

            mouse.x = (ev.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(ev.clientY / window.innerHeight) * 2 + 1;

            console.log(mouse)
            raycaster.setFromCamera(mouse, camera);

            console.log(raycaster)

            // 这里我们只检测模型的选中情况
            let intersects = raycaster.intersectObjects(gltf.scene.children, true);
            console.log(9999999999999)
            console.log(intersects)
            console.log(gltf.scene.children)




            if (intersects.length > 0) {
                //   console.log(intersects)
                let selectedObjects = intersects[0].object;
                changecolor(selectedObjects)
                //
                // for ( let i = 0; i < intersects.length; i ++ ) {
                //    // intersects[ i ].object.material.color.set( 0xff0000 );
                // }

            }
        }
        if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
            console.log("手机访问.");
            $(document).on('click touchend',function(e){
                selectHandler(e)
                console.log("2222222222xxxxxxxxxxx")
                //  location.href = $(this).attr('data-url');
                //  return false;
            });
        }else{
            document.body.addEventListener('click', selectHandler, false);

            console.log("电脑访问.");
        }



      //  document.body.addEventListener('click', selectHandler, false);
    }


    function changecolor(selectedObjects){
        let newMaterial = selectedObjects.material.clone();
        console.log("dianjixxxxxxxxxx")
        console.log(selectedObjects)
        let oldMaterialObj  = selectedObjects.material.clone();

        let color = newMaterial.color

        if(oldSelect && oldMaterial){
            console.log( oldMaterial )
            if(oldSelect.uuid == selectedObjects.uuid){
                newMaterial = oldMaterial
                //     newMaterial.color
                console.log(  newMaterial.color )
                oldMaterial = ''
                oldSelect = ''
                console.log("2222222222222")
            }else{
                console.log("111111111111222222")
                oldSelect.material = oldMaterial
                oldMaterial = ''
                oldSelect = ''
                oldSelect =  selectedObjects
                oldMaterial = oldMaterialObj
                newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
                console.log(  newMaterial.color )
            }

        }else{
            console.log("111111111111")
            oldSelect =  selectedObjects
            oldMaterial = oldMaterialObj
            newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
            console.log(  newMaterial.color )
        }

        let  uuidKey = selectedObjects.userData.UniqueId


        let html = "<div class='tableTop'>\n"


        html+="    <div class='table border'>\n" +
            "        <div class='text-right dleft border'>name:</div>\n" +
            "        <div class='text-left dright'>"+selectedObjects.name+"</div>\n" +
            "    </div>\n"

        html+="    <div class='table border'>\n" +
            "        <div class='text-right dleft border'>uuid:</div>\n" +
            "        <div class='text-left dright'>"+selectedObjects.uuid+"</div>\n" +
            "    </div>\n"
        if(jsondata[uuidKey]){
            let danwei = "M"
            let rows = jsondata[uuidKey]

            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>项目名称:</div>\n" +
                "        <div class='text-left dright'>"+rows.ProjectName+"</div>\n" +
                "    </div>\n"

            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>类型:</div>\n" +
                "        <div class='text-left dright'>"+rows.Type+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>长:</div>\n" +
                "        <div class='text-left dright'>"+rows.Length+danwei+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>宽:</div>\n" +
                "        <div class='text-left dright'>"+rows.Width+danwei+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>厚/高:</div>\n" +
                "        <div class='text-left dright'>"+rows.Height+danwei+"</div>\n" +
                "    </div>\n"


        }

        html+="</div>"
        $.dialog({id:'testID2'}).close();
        $.dialog({
            top:"100%",
            width:"100%",
            id: 'testID2',
            content: html
        });
        selectedObjects.material = newMaterial;
        render()
    }
    createGUI()
    // 创建ui界面
    function createGUI() {
        return

        if ( gui ) gui.destroy();

        gui = new GUI( { width: 400 } );

        // SHADOW


        let  guiData={
            drawStrokes:true,
            drawFillShapes:4,
            strokesWireframe:true,
            fillShapesWireframe:true,
        }



        gui = new GUI( { width: 350 } );
        gui.addFolder( "Shadow" );

        gui.add( guiData, 'drawStrokes' ).name( 'Draw strokes' ).onChange( update );

        gui.add( guiData, 'drawFillShapes',1,100 ).name( 'Draw fill shapes' ).onChange( update );

        gui.add( guiData, 'strokesWireframe' ).name( 'Wireframe strokes' ).onChange( update );

        gui.add( guiData, 'fillShapesWireframe' ).name( 'Wireframe fill shapes' ).onChange( update );


        function update() {

        }

    }


    //清理效果
    function cleaningEffect(){


    }


    //内存  帧数 仪表
    function dostats(){
        stats = new Stats();

        $("#stat").html( stats.dom)

    }

    function render() {
        //  composerAll.render();
        renderer.render( scene, camera );
        stats.update()

    }



</script>



<script>
$(function(){
    let h  =$(window).height()
    $(".box").height(h)
    $(".left a ").eq(1).addClass("hover")
    $(".left a ").click(function(){
        $(".left a ").removeClass("hover")
        $(this).addClass("hover")

    })
})

</script>

</body>
</html>
